package cn.sail.shiroAuthenticator.security;

import cn.sail.shiroAuthenticator.pojo.entity.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义Realm
 */
public class CustomRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(CustomRealm.class);
    /**
     * 授权验证
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    private List<User> users = new ArrayList<>(2);
    {
        User jerry = new User();
        jerry.setUserName("jerry");
        jerry.setPassword("123456");
        users.add(jerry);
        User yxj = new User();
        yxj.setUserName("yxj");
        yxj.setPassword("123456789");
        users.add(yxj);
    }

    /**
     * 身份认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取请求用户名信息
        String tokenUserName = (String) authenticationToken.getPrincipal();
        //判断用户是否存在
        User dbUser = new User();
        for(User user:users){
            //用户存在
            if(tokenUserName == user.getUserName()){
                dbUser.setUserName(user.getUserName());
                dbUser.setPassword(user.getPassword());
            }
        }
        //用户不存在
        if(dbUser.getUserName() == null){
            logger.warn("doGetAuthenticationInfo failed. 用户不存在. tokenUserName:{}", tokenUserName);
            return null;
        }

        //用户存在，返回用户信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(dbUser.getUserName(), dbUser.getPassword(), "testRealm");
        return authenticationInfo;

    }
}
